package com.example.androidlearning2200.http;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * 网络请求工具类
 */
public class HttpUtil {

    /**
     * 通用Post请求
     *
     * @param urlString
     * @param params
     * @param callback
     */
    public static void doPost(String urlString, Map<String, String> params, HttpCallback callback) {
        new Thread(() -> {
            try {
                // 创建 URL 对象
                URL url = new URL(urlString);
                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置请求方式为POST请求
                connection.setRequestMethod("POST");
                // 设置请求头
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                // 构建 POST 请求的参数
                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    postData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                postData.delete(postData.length() - 1, postData.length());
                // 发送 POST 请求
                connection.getOutputStream().write(postData.toString().getBytes("UTF-8"));
                // 建立连接
                connection.connect();
                // 获取响应码
                int responseCode = connection.getResponseCode();
                // 检查响应码
                if (responseCode == 200) {
                    // 获取响应内容
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    callback.onHttpSucceed(response.toString());
                } else {
                    System.out.println("请求失败，响应码: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


    /**
     * 通用Get请求
     *
     * @param urlStr
     * @param callback
     */
    public static void doGet(String urlStr, HttpCallback callback) {
        new Thread(() -> {
            try {
                // 创建 URL 对象
                URL url = new URL(urlStr);
                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置请求方式为GET请求
                connection.setRequestMethod("GET");
                // 建立连接
                connection.connect();
                // 获取响应码
                int responseCode = connection.getResponseCode();
                // 检查响应码
                if (responseCode == 200) {
                    // 获取响应内容
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    callback.onHttpSucceed(response.toString());
                } else {
                    System.out.println("请求失败，响应码: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


    /**
     * 通用文件下载
     *
     * @param downloadUrl
     * @param outputFile
     */
    public static void downloadFile(String downloadUrl, String outputFile) {
        new Thread(() -> {
            try {
                // 创建 URL 对象
                URL url = new URL(downloadUrl);
                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                // 建立连接
                connection.connect();
                // 获取响应码
                int responseCode = connection.getResponseCode();
                // 检查响应码
                if (responseCode == 200) {
                    // 获取输入流，用于读取响应内容
                    InputStream inputStream = connection.getInputStream();
                    // 创建输出流，用于保存下载的文件
                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                    // 缓冲区
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    // 关闭输入流和输出流
                    inputStream.close();
                    outputStream.close();
                    System.out.println("文件下载成功！");
                } else {
                    System.out.println("请求失败，响应码: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
